//
//  CAAppDelegate.m
//  qiche
//
//  Created by Seimei on 12-11-6.
//  Copyright (c) 2012年 iCar. All rights reserved.
//

#import "CAAppDelegate.h"

#import "CAFirstViewController.h"

#import "CASecondViewController.h"

#import "CATestViewController.h"

#import "CAForthViewController.h"

#import "CAMoreViewController.h"

#import "CAViewController.h"

#import "CAUserInit.h"
#import "CALoginViewController.h"

@implementation CAAppDelegate
@synthesize window=_window;
@synthesize tabBarController=_tabBarController;
@synthesize device=_device;
@synthesize carVin=_carVin;
@synthesize carVinList=carVinList;
@synthesize userName=_userName;
@synthesize weiboObjectList = _weiboObjectList;

+ (CAAppDelegate *)globalAppdelegate {
	return (CAAppDelegate*)[UIApplication sharedApplication].delegate;
}

- (void)dealloc
{
    [_window release];
    [_tabBarController release];
    [_device release];
    [carVinList release];
    self.userName = nil;
    self.weiboObjectList = nil;
    self.carVin = nil;
    [super dealloc];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
    // Override point for customization after application launch.
    
    CALoginViewController *loginController = [[CALoginViewController alloc] initWithNibName:@"CALoginViewController" bundle:nil];
    self.window.rootViewController = loginController;
    [loginController release];
    
    [self.window makeKeyAndVisible];
 
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    UIApplication* app = [UIApplication sharedApplication];
    
    BOOL backgroundAccepted = [app setKeepAliveTimeout:600 handler:^{
        [self backgroundHandler];
    }];
    
    bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
        [app endBackgroundTask:bgTask];
        bgTask = UIBackgroundTaskInvalid;
    }];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,
                                             0), ^{
        // Do the work associated with the task.
        //        NSTimer *timer = [NSTimer timerWithTimeInterval:1.5
        //                                         target:self
        //                                       selector:@selector(testload)
        //                                       userInfo:nil
        //                                        repeats:YES];
        //        [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
        //        [[NSRunLoop currentRunLoop] run];
        
        
    });

}

- (void) backgroundHandler
{
    //[_cars readOdbData];
    NSLog(@"background called");
    
    UIApplication* app = [UIApplication sharedApplication];
    bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
        [app endBackgroundTask:bgTask];
        bgTask = UIBackgroundTaskInvalid;
    }];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,
                                             0), ^{
        // Do the work associated with the task.
        while (1) {
            NSLog(@".....");
            sleep(1);
        }
        
    });
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

/*
// Optional UITabBarControllerDelegate method.
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController
{
}
*/

/*
// Optional UITabBarControllerDelegate method.
- (void)tabBarController:(UITabBarController *)tabBarController didEndCustomizingViewControllers:(NSArray *)viewControllers changed:(BOOL)changed
{
}
*/

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    //	NSLog(@"获得已授权的key:%@",url);
    
    //    [[WBShareKit mainShare] handleOpenURL:url];
    
    
    return YES;
}

- (void) applicationSwitchRoot
{
    
    UIViewController *viewController1 = [[CAViewController alloc] initWithNibName:@"CAViewController" bundle:nil];
    UINavigationController *navCtrl1=[[UINavigationController alloc]initWithRootViewController:viewController1];
    navCtrl1.navigationBar.barStyle = UIBarStyleBlack;
    [viewController1 release];
    UIViewController *viewController2 = [[CASecondViewController alloc] initWithNibName:@"CASecondViewController" bundle:nil] ;
    UINavigationController *navCtrl2=[[UINavigationController alloc]initWithRootViewController:viewController2];
    navCtrl2.navigationBar.barStyle = UIBarStyleBlack;
    [viewController2 release];
    UIViewController *viewController3 = [[CATestViewController alloc] initWithNibName:@"CATestViewController" bundle:nil] ;
    UINavigationController *navCtrl3=[[UINavigationController alloc]initWithRootViewController:viewController3];
    navCtrl3.navigationBar.barStyle = UIBarStyleBlack;
    [viewController3 release];
    UIViewController *viewController4 = [[CAForthViewController alloc] initWithNibName:@"CAForthViewController" bundle:nil] ;
    UINavigationController *navCtrl4=[[UINavigationController alloc]initWithRootViewController:viewController4];
    navCtrl4.navigationBar.barStyle = UIBarStyleBlack;
    [viewController4 release];
    UIViewController *viewController5 = [[CAMoreViewController alloc] initWithNibName:@"CAMoreViewController" bundle:nil] ;
    UINavigationController *navCtrl5=[[UINavigationController alloc]initWithRootViewController:viewController5];
    navCtrl5.navigationBar.barStyle = UIBarStyleBlack;
    [viewController5 release];
    
    
    self.tabBarController = [[[UITabBarController alloc] init] autorelease];
    self.tabBarController.viewControllers = [NSArray arrayWithObjects:navCtrl1, navCtrl2, navCtrl3,navCtrl4,navCtrl5,nil];
    
    //    navController = [[UINavigationController alloc] initWithRootViewController:self.tabBarController];
    //    navController.navigationBar.barStyle = UIBarStyleBlack;
    self.window.rootViewController = self.tabBarController;
    [self.window makeKeyAndVisible];
    [navCtrl1 release];
    [navCtrl2 release];
    [navCtrl3 release];
    [navCtrl4 release];
    [navCtrl5 release];
}

- (void) background_send {
    //[_device readOdbDatap];
    while (1) {
        [_device readOdbDatap];
        usleep(5000);
    }
}

- (void) calc {
    while (1) {
        [SensorsService calculateTraveData];
        
        NSLog(@"时速->%f,转速->%f,压力->%f,空气流量->%f"
              , [SensorsService vehicleSpeed], [SensorsService engineRpm], [SensorsService map], [SensorsService airFlowRate]);
        NSLog(@"行车时间->%d,停车时间->%d,总行车时间->%d,平均时速->%f,平均油耗->%f,平均油门->%f"
              , [SensorsService travelTime], [SensorsService stopTime]
              , [SensorsService totalTime], [SensorsService avgVehicleSpeed]
              , [SensorsService avgFuel], [SensorsService avgAcceleratorPedalPosition]);
        sleep(1);
    }
}

- (void) myTask
{
//    _device = [[CACar alloc] init];
//    [_device connect];
    
//    NSTimer *t = [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(background_send) userInfo:nil repeats:YES];
//    [[NSRunLoop mainRunLoop] addTimer:t forMode:NSDefaultRunLoopMode];
    
    HUD.mode = MBProgressHUDModeDeterminate;
	HUD.labelText = @"正在检测协议...";
	float progress = 0.0f;
    NSLog(@"---->");
    //[SensorsService test:_device];
    while (![SensorsService detectProtocol:_device])
	{
		progress += 0.001f;
		HUD.progress = progress;
		usleep(5000);
	}
    
    usleep(5000);
    
    NSString *_vin = [SensorsService vinCode:_device];
    if ([_vin length] != 17) {
        [[NSUserDefaults standardUserDefaults] setValue:@"" forKey:@"vin_code"];
    }
    else
    {
        [[NSUserDefaults standardUserDefaults] setValue:_vin forKey:@"vin_code"];
    }
    
    [[NSUserDefaults standardUserDefaults] synchronize];
    if([self.window.rootViewController respondsToSelector:@selector(set_vin_code:)])
    {
        
        [self.window.rootViewController performSelector:@selector(set_vin_code:) withObject:_vin];
        
    }
	// Back to indeterminate mode
	HUD.mode = MBProgressHUDModeIndeterminate;
	HUD.labelText = @"检测成功";
    //sleep(3);
}

- (BOOL) willShowInit
{
    if(![[NSUserDefaults standardUserDefaults] objectForKey:@"vin_code"])
    {
        return YES;
    }
    
    if(![[NSUserDefaults standardUserDefaults] objectForKey:@"car_number"])
    {
        return YES;
    }
    
    if(![[NSUserDefaults standardUserDefaults] objectForKey:@"car_miles"])
    {
        return YES;
    }
    
    return NO;
}

#pragma mark -
#pragma mark MBProgressHUDDelegate methods

- (void)hudWasHidden:(MBProgressHUD *)hud {
	// Remove HUD from screen when the HUD was hidded
	[HUD removeFromSuperview];
	[HUD release];
	HUD = nil;
    
    //NSTimer *t = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(background_send) userInfo:nil repeats:YES];
    //[[NSRunLoop mainRunLoop] addTimer:t forMode:NSDefaultRunLoopMode];
    //[_device  performSelectorInBackground:@selector(readOdbDatap) withObject:nil];
    [self performSelectorInBackground:@selector(background_send) withObject:nil];
    
    //NSTimer *t2 = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(calc) userInfo:nil repeats:YES];
    //[[NSRunLoop mainRunLoop] addTimer:t2 forMode:NSDefaultRunLoopMode];
    [self  performSelectorInBackground:@selector(calc) withObject:nil];
    
}

-(void)parseLoginReturn:(id)sender
{
    NSDictionary* dic = (NSDictionary*)sender;
    NSString *err = [dic valueForKey:NETERR];
    if (err && [err length] > 0)
    {
        return;
    }
    
}

- (void) initView
{
    if(![self willShowInit])
    {
        UIViewController *viewController1 = [[CAViewController alloc] initWithNibName:@"CAViewController" bundle:nil];
        UINavigationController *navCtrl1=[[UINavigationController alloc]initWithRootViewController:viewController1];
        navCtrl1.navigationBar.barStyle = UIBarStyleBlack;
        [viewController1 release];
        UIViewController *viewController2 = [[CASecondViewController alloc] initWithNibName:@"CASecondViewController" bundle:nil] ;
        UINavigationController *navCtrl2=[[UINavigationController alloc]initWithRootViewController:viewController2];
        navCtrl2.navigationBar.barStyle = UIBarStyleBlack;
        [viewController2 release];
        UIViewController *viewController3 = [[CATestViewController alloc] initWithNibName:@"CATestViewController" bundle:nil] ;
        UINavigationController *navCtrl3=[[UINavigationController alloc]initWithRootViewController:viewController3];
        navCtrl3.navigationBar.barStyle = UIBarStyleBlack;
        [viewController3 release];
        UIViewController *viewController4 = [[CAForthViewController alloc] initWithNibName:@"CAForthViewController" bundle:nil] ;
        UINavigationController *navCtrl4=[[UINavigationController alloc]initWithRootViewController:viewController4];
        navCtrl4.navigationBar.barStyle = UIBarStyleBlack;
        [viewController4 release];
        UIViewController *viewController5 = [[CAMoreViewController alloc] initWithNibName:@"CAMoreViewController" bundle:nil] ;
        UINavigationController *navCtrl5=[[UINavigationController alloc]initWithRootViewController:viewController5];
        navCtrl5.navigationBar.barStyle = UIBarStyleBlack;
        [viewController5 release];
        
        self.tabBarController = [[[UITabBarController alloc] init] autorelease];
        self.tabBarController.viewControllers = [NSArray arrayWithObjects:navCtrl1, navCtrl2, navCtrl3,navCtrl4,navCtrl5,nil];
        
        self.window.rootViewController = self.tabBarController;
        [navCtrl1 release];
        [navCtrl2 release];
        [navCtrl3 release];
        [navCtrl4 release];
        [navCtrl5 release];
    }
    else
    {
        UIViewController *init = [[CAUserInit alloc] initWithNibName:@"CAUserInit" bundle:nil];
        self.window.rootViewController = init;
        [init release];
    }
    
    
//    HUD = [[MBProgressHUD alloc] initWithView:self.window.rootViewController.view];
//	[self.window.rootViewController.view addSubview:HUD];
//	
//	HUD.delegate = self;
//	HUD.labelText = @"正在连接汽车...";
//    HUD.minSize = CGSizeMake(135.f, 135.f);
//    
//    _device = [[CACar alloc] init];
//    BOOL st = [_device connect];
//    
//    if(!st)
//    {
//        [HUD show:YES];
//    }
//    else
//    {
//        [HUD showWhileExecuting:@selector(myTask) onTarget:self withObject:nil animated:YES];
//        
//    }
}

@end
